import { app, dialog } from "electron";
import path from "path";
import logger from "./log";
import { autoUpdater } from "electron-updater";

export default function checkUpdate(mainWindow) {
  console.log("process.platform", process.platform);

  // if (process.platform == "darwin") {
  //   autoUpdater.setFeedURL(
  //     "https://github.com/keep-deep-think/electron-todolist/releases/latest.yml?noCache=1i3mfdvk0"
  //   ); //设置要检测更新的路径
  // } else {
  // autoUpdater.setFeedURL({
  //   provider: "github",
  //   owner: "keep-deep-think",
  //   repo: "electron-todolist",
  //   token: "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",
  //   releaseType: "release",
  // });
  // logger.info("http://localhost:9000");
  autoUpdater.setFeedURL("http://localhost:9000"); //设置要检测更新的路径
  // }

  const isDevelopment = process.env.NODE_ENV === "development";

  // 防止报错no such file or directory dev-app-update.yml
  if (isDevelopment) {
    // 强制在开发环境进行更新
    autoUpdater.forceDevUpdateConfig = true;
  }
  logger.info("checkUpdate-检测更新");
  //检测更新
  autoUpdater.checkForUpdates();

  //监听'error'事件
  autoUpdater.on("error", (err) => {
    console.log("出错:", err);
    logger.info(`出错-检测更新 ${JSON.stringify(err)}`);
  });

  //监听'update-available'事件，发现有新版本时触发
  autoUpdater.on("update-available", () => {
    console.log("found new version");
    mainWindow.webContents.send("debug", "发现新版本...");
  });

  //默认会自动下载新版本，如果不想自动下载，设置autoUpdater.autoDownload = false

  autoUpdater.on("download-progress", (progressObj) => {
    console.log(`Download speed: ${progressObj.bytesPerSecond}`);
    console.log(`Downloaded ${progressObj.percent}%`);
    console.log(`Transferred ${progressObj.transferred}/${progressObj.total}`);
    // 输出日志
    logger.info(`Downloaded ${progressObj.percent}%`);
    mainWindow.webContents.send("debug", `下载进度 ${progressObj.percent}%`);
  });
  //监听'update-downloaded'事件，新版本下载完成时触发
  autoUpdater.on("update-downloaded", () => {
    dialog
      .showMessageBox({
        type: "info",
        title: "应用更新",
        message: "发现新版本，是否更新？",
        buttons: ["是", "否"],
      })
      .then((buttonIndex) => {
        if (buttonIndex.response == 0) {
          //选择是，则退出程序，安装新版本
          autoUpdater.quitAndInstall();
          app.quit();
        }
      });
  });
}
